package edu.ck.drawImageTest;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;

public class drawImageTestView extends View{
	private Bitmap image;
	
	private int px = 0;
	private int py = 0;
	private int vx = 10;
	private int vy = 10;
	
	private int touchX;
	private int touchY;
	private int touchAction;
	private boolean bGoingTarget;
	
	public drawImageTestView(Context context){
		super(context);
		setBackgroundColor(Color.WHITE);
		
		setFocusable(true);
		bGoingTarget = false;
		Resources r = context.getResources();
		image = BitmapFactory.decodeResource(r, R.drawable.sample);
	}
		
	@Override
	protected void onDraw(Canvas canvas){
		Paint paint = new Paint();
		canvas.drawBitmap(image, px-40, py-40, paint);
		
		if(px<0 || getWidth() < px) vx = -vx;
		if(py<0 || getHeight() < py) vy = -vy;
		
		if(bGoingTarget){
		px += vx;
		py += vy;
		}
		if(touchAction == MotionEvent.ACTION_DOWN){
			bGoingTarget = false;
			px = touchX;
			py = touchY;
		}
		else if(touchAction == MotionEvent.ACTION_UP){
			bGoingTarget = true;
		}
		else if(touchAction == MotionEvent.ACTION_MOVE){
			bGoingTarget = false;
			px = touchX;
			py = touchY;
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event){
		touchX = (int)event.getX();
		touchY = (int)event.getY();
		touchAction = event.getAction();
		return true;
	}
}
